package cn.gdust.servlet;

import cn.gdust.dao.CommentDao;
import cn.gdust.entity.Comment;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/AddCommentServlet.do")
public class AddCommentServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            // 设置请求体的编码格式
            request.setCharacterEncoding("UTF-8");
            // 从请求体中获取JSON数据
            String json = request.getReader().lines().reduce("", (accumulator, actual) -> accumulator + actual);

            // 使用Gson将JSON数据转换为Barrage对象
            Gson gson = new Gson();
            Comment comment = gson.fromJson(json, Comment.class);

            CommentDao commentDao = new CommentDao();
            String count = String.valueOf(commentDao.addComment(comment));
            response.getWriter().write(count);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
